package com.project.dao.imp;

import com.project.bean.ClassBean;
import com.project.bean.RoomBean;
import com.project.dao.IClassDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Repository
public class IClassDaoImp extends BaseDao implements IClassDao {
    @Override
    public List<ClassBean> findAll() {
        List<ClassBean> list = new ArrayList<>();
        this.setConnection();
        try {
            ps = con.prepareCall("select * from r_class");

            re = ps.executeQuery();
            while (re.next()) {
                ClassBean classBean = new ClassBean();
                classBean.setId(re.getInt("pk_classId"));
                classBean.setName(re.getString("r_className"));
//                classBean.setStartDate(LocalDate.parse(re.getString("r_startDate")));
                classBean.setTeacher(re.getString("r_teacher"));
                String day = re.getString("r_startDate");
                classBean.setStartDate(day!=null ? LocalDate.parse(day):null);

                list.add(classBean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
        return list;
    }

    @Override
    public void add(ClassBean classBean) {
        this.setConnection();
        try {
            ps = con.prepareCall("INSERT INTO r_class(r_className,r_startDate,r_teacher)" +
                    "VALUES(?,?,?)");
            ps.setObject(1, classBean.getName());
            ps.setObject(2, classBean.getStartDate());
            ps.setObject(3, classBean.getTeacher());

            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
    }

    @Override
    public void del(Integer id) {
        this.setConnection();
        try {
            ps = con.prepareCall("delete from r_class where pk_classId = ?");
            ps.setObject(1, id);

            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
    }

    @Override
    public ClassBean findByName(String name) {
        ClassBean classBean = null;
        this.setConnection();
        try {
            ps = con.prepareCall("select * from r_class where r_className = ? ");
            ps.setObject(1, name);

            re = ps.executeQuery();
            if (re.next()) {
                classBean = new ClassBean();
                classBean.setId(re.getInt("pk_classId"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
        return classBean;
    }

}
